//
//  AppModel.m
//  ZZBlue
//
//  Created by evan on 2017/10/26.
//  Copyright © 2017年 stonesMonkey. All rights reserved.
//

#import "AppModel.h"

#define kAppModelPath @"appModel.plist"
#define kAppKey @"appKey"

@implementation AppModel

+ (instancetype)shareInstance {

    static AppModel* model = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        // 从数据中拿
        NSString *path = NSHomeDirectory();
        path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",kAppModelPath]];
        NSData *myData = [NSData dataWithContentsOfFile:path];
        //创建反归档对象
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:myData];
        //反归档
        model = [unarchiver decodeObjectForKey:kAppKey];
        //完成反归档
        [unarchiver finishDecoding];
        if(model == nil) {

            model = [[self alloc] init];
            model.homeAReact = CGRectMake(50, 50, 40, 40);
            model.homeBReact = CGRectMake(150, 150, 28, 28);
            model.homeIndexModel = 0;
            model.homeLightValue = 0;
        }

    });

    return model;
}


-(void)encodeWithCoder:(NSCoder *)aCoder
{

    [aCoder encodeCGRect:self.homeAReact forKey:@"homeAReact"];
    [aCoder encodeCGRect:self.homeBReact forKey:@"homeBReact"];
     [aCoder encodeFloat:self.homeLightValue forKey:@"homeLightValue"];
     [aCoder encodeInteger:self.homeIndexModel forKey:@"homeIndexModel"];
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {

        self.homeAReact = [aDecoder decodeCGRectForKey:@"homeAReact"];
        self.homeBReact = [aDecoder decodeCGRectForKey:@"homeBReact"];
        self.homeLightValue = [aDecoder decodeFloatForKey:@"homeLightValue"];
        self.homeIndexModel = [aDecoder decodeIntegerForKey:@"homeIndexModel"];

    }
    return self;
}

- (void)save {

    //准备路径:
    NSString *path = NSHomeDirectory();
    NSLog(@"%@",path);

    path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",kAppModelPath]];
    //1:准备存储数据的对象
    NSMutableData *data = [NSMutableData data];
    //2:创建归档对象
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    //3:开始归档
    [archiver encodeObject:self forKey:kAppKey];
    //4:完成归档
    [archiver finishEncoding];
    //5:写入文件当中
    BOOL result = [data writeToFile:path atomically:YES];
    if (result) {

        // 写入成功
    }
}

@end
